import "./captcha.scss"
import Slider from "./slider/slider"
import Slider2 from "./slider2/slider2"
import Rotate from "./rotate/rotate";
import Concat from "./concat/concat";
import WordImageClick from "./word_image_click/word_image_click";
import ImageClick from "./image_click/image_click";
import WordOrderImageClick from "./word_order_image_click/word_order_image_click";
import RotateDegree from "./rotate_degree/rotate_degree";
import Scrape from "./scrape/scrape";
import Disable from "./disable/disable";
import {CaptchaConfig, wrapConfig, wrapStyle} from "./config/config";
import {clearAllPreventDefault} from "./common/common";
import Curve from "./curve/curve";

const template =
    `
<div id="tianai-captcha-container">
    <div id="tianai-captcha-load-box" class="loading">
        <span></span>
        <span></span>
        <span></span>
        <span></span>
        <span></span>
</div>
    <div id="tianai-captcha-parent">
        <div id="tianai-captcha-bg-img"></div>
        <div id="tianai-captcha-box">
            <div id="tianai-captcha-loading" class="loading"></div>
        </div>
        <!-- 底部 -->
        <div class="slider-bottom">
<!--            <img class="logo" id="tianai-captcha-logo" src=""></img>-->
            <div class="close-btn" id="tianai-captcha-slider-close-btn"></div>
            <div class="refresh-btn" id="tianai-captcha-slider-refresh-btn"></div>
        </div>
    </div>
    </div>
    `;

function createCaptchaByType(type, styleConfig) {
    switch (type) {
        case "SLIDER":
            return new Slider("#tianai-captcha-box", styleConfig);
        case "IMAGE_CLICK":
            return new ImageClick("#tianai-captcha-box", styleConfig);
        case "HONEYCOMB_IMAGE_CLICK":
            return new ImageClick("#tianai-captcha-box", styleConfig);
        case "WORD_IMAGE_CLICK":
            return new WordImageClick("#tianai-captcha-box", styleConfig);
        case "DISABLED":
            return new Disable("#tianai-captcha-box", styleConfig);
        case "CURVE":
            return new Curve("#tianai-captcha-box", styleConfig);
        case "ROTATE":
            return new Rotate("#tianai-captcha-box", styleConfig);
        case "CONCAT":
            return new Concat("#tianai-captcha-box", styleConfig);
        case "WORD_ORDER_IMAGE_CLICK":
            return new WordOrderImageClick("#tianai-captcha-box", styleConfig);
        case "SCRAPE":
            return new Scrape("#tianai-captcha-box", styleConfig);
        case "ROTATE_DEGREE":
            return new RotateDegree("#tianai-captcha-box", styleConfig);
        case "SLIDER2":
            return new Slider2("#tianai-captcha-box", styleConfig);
        default:
            return null;
    }
}

class TianAiCaptcha {
    constructor(config, style) {
        this.config = wrapConfig(config);
        if (this.config.btnRefreshFun) {
            this.btnRefreshFun = this.config.btnRefreshFun;
        }
        if (this.config.btnCloseFun) {
            this.btnCloseFun = this.config.btnCloseFun;
        }
        this.style = wrapStyle(style);
    }

    init() {
        this.destroyWindow();
        this.config.domBindEl.append(template);
        this.domTemplate = this.config.domBindEl.find("#tianai-captcha-container");
        clearAllPreventDefault(this.domTemplate);
        this.loadStyle();
        // 绑定按钮事件
        this.config.domBindEl.find("#tianai-captcha-slider-refresh-btn").click((el) => {
            this.btnRefreshFun(el, this);
        });
        this.config.domBindEl.find("#tianai-captcha-slider-close-btn").click((el) => {
            this.btnCloseFun(el, this);
        });
        try {
            // 加载验证码
            this.reloadCaptcha();
        }catch (e) {
            alert('验证加载失败')
        }
        return this;
    }

    btnRefreshFun(el, tac) {
        tac.reloadCaptcha();
    }

    btnCloseFun(el, tac) {
        tac.destroyWindow();
    }

    reloadCaptcha() {
        this.showLoading(true);
        // debugger;
        this.destroyCaptcha(() => {
            this.createCaptcha();
        })
    }

    showLoading(inner = false) {
        if (inner) {
            this.config.domBindEl.find("#tianai-captcha-loading").css("display", "block");
        } else {
            this.config.domBindEl.find('#tianai-captcha-load-box').css('display', 'block');
        }
    }

    closeLoading() {
        if(this.config.domBindEl.find('#tianai-captcha-parent')) {
            this.config.domBindEl.find('#tianai-captcha-load-box').css({"display": "none"});
            this.config.domBindEl.find("#tianai-captcha-loading").css("display", "none");
        }
    }

    loadStyle() {
        // 设置样式
        const bgUrl = this.style.bgUrl;
        const logoUrl = this.style.logoUrl;
        if (bgUrl) {
            // 背景图片
            this.config.domBindEl.find("#tianai-captcha-bg-img").css("background-image", "url(" + bgUrl + ")");
        }
        if (logoUrl && logoUrl !== "") {
            // logo
            this.config.domBindEl.find("#tianai-captcha-logo").attr("src", logoUrl);
        } else if (logoUrl === null) {
            // 删除logo
            this.config.domBindEl.find("#tianai-captcha-logo").css("display", "none");
        }
    }

    destroyWindow() {
        window.currentCaptcha = undefined;
        if (this.domTemplate) {
            this.domTemplate.remove();
        }
    }

    openCaptcha() {
        var parent = this.config.domBindEl.find('#tianai-captcha-parent');
        parent.css({'display': 'block'});

        setTimeout(() => {
            parent.css({opacity: 1});
            // window.currentCaptcha.el.css("transform", "translateX(0)")
        }, 20)
    }

    createCaptcha() {
        this.config.requestCaptchaData().then(data => {

            const captcha = createCaptchaByType(data.captcha.type, this.style);
            if (captcha == null) {
                throw new Error("[TAC] 未知的验证码类型[" + data.captcha.type + "]");
            }
            captcha.init(data, (d, c) => {
                // 验证
                const currentCaptchaData = c.currentCaptchaData;
                const data = {
                    bgImageWidth: currentCaptchaData.bgImageWidth,
                    bgImageHeight: currentCaptchaData.bgImageHeight,
                    templateImageWidth: currentCaptchaData.templateImageWidth,
                    templateImageHeight: currentCaptchaData.templateImageHeight,
                    startTime: currentCaptchaData.startTime,
                    stopTime: currentCaptchaData.stopTime,
                    trackList: currentCaptchaData.trackList,
                    left: currentCaptchaData.left,
                    top: currentCaptchaData.top
                };
                if (c.type === 'ROTATE_DEGREE' || c.type === 'ROTATE') {
                    data.bgImageWidth = c.currentCaptchaData.end;
                }
                if (currentCaptchaData.data) {
                    data.data = currentCaptchaData.data;
                }
                // 清空
                const id = c.currentCaptchaData.currentCaptchaId;
                c.currentCaptchaData = undefined;
                // 调用验证接口
                this.config.validCaptcha(id, data, c, this)
            })
            setTimeout(() => {
                this.closeLoading();
                this.openCaptcha()
            }, 10)

        }).catch(e=>{
            //加载失败，销毁
            alert('验证码加载失败')

            this.destroyWindow()
        });
    }

    destroyCaptcha(callback) {
        if (window.currentCaptcha) {
            // window.currentCaptcha.el.css("transform", "translateX(300px)")
            window.currentCaptcha.el.css("display", "none")
            setTimeout(() => {
                    if (window.currentCaptcha) {
                        window.currentCaptcha.destroy();
                    }
                    if (callback) {
                        callback();
                    }
                }
                ,
                500
            )
        } else {
            callback();
        }
    }


}

export {TianAiCaptcha, CaptchaConfig}
